<?php
/**
* mcrypt library
*/
	
class Encryption
{
	function __construct($cipher=MCRYPT_RIJNDAEL_128, $mode=MCRYPT_MODE_ECB, $key='defaultkey'){
		$this->cipher = $cipher;//"MCRYPT_3DES", "MCRYPT_XTEA", "MCRYPT_RIJNDAEL_256"
		$this->mode = $mode;//"ECB", "CBC", "cfb", "ofb", "nofb" , "stream".
		$this->key = substr(($key), 0, 16);
	}
	
	function encrypt($data)
	{
		$iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
		$result = mcrypt_encrypt( $this->cipher, $this->key, $data, $this->mode, $iv);
		return $this->changeChar('e', $result);
	}
	
	function decrypt($data)
	{
		$iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
		$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
		$data = $this->changeChar('d', $data);
		$result = mcrypt_decrypt( $this->cipher, $this->key, $data, $this->mode, $iv);
		$result = trim($this->changeChar('e', $result), '0');
		return $this->changeChar('d', $result);
	}
	
	function sencrypt($string)
	{
		$result = '';
		for($i=1; $i<=strlen($string); $i++) {
			$char = substr($string, $i-1, 1);
			$keychar = substr($this->key, ($i % strlen($this->key))-1, 1);
			$char = chr(ord($char)+ord($keychar));
			$result.=$char;
		}
		return $this->changeChar('e', $result);
	}
	
	function sdecrypt($string)
	{
		$result = '';
		$string = $this->toChar('d', $string);
		for($i=1; $i<=strlen($string); $i++) {
			$char = substr($string, $i-1, 1);
			$keychar = substr($this->key, ($i % strlen($this->key))-1, 1);
			$char = chr(ord($char)-ord($keychar));
			$result.=$char;
		}
		return $result;
	}
	
	private function changeChar($type, $data) 
	{
		if ($type == 'e') {
			return bin2hex($data);
		} else if($type == 'd') {
		    $len = strlen($data); 
		    return pack("H" . $len, $data); 			
		}
		return false;
	}
}